package com.czk.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/18 22:57
 */
@RestController
public class LoginController {
    @PostMapping(value = "/login-success", produces = {"text/plain;charset=utf-8"})
    public String loginSuccess() {
        return getUsername() + "登陆成功";
    }

    /**
     * session验证
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=utf-8"})
    // 拥有p1权限才能访问
    @PreAuthorize("hasAnyAuthority('p1')")
    public String rl(HttpSession session) {
        return "访问r1了";
    }

    /**
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=utf-8"})
    // 拥有p2权限才能访问
    @PreAuthorize("hasAnyAuthority('p2')")
    public String r2(HttpSession session) {
        return "访问r2";
    }

    /**
     * 拿到用户信息
     *
     * @return
     */
    private String getUsername() {
        String username;
        // 拿到用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 拿到用户身份
        Object credentials = authentication.getPrincipal();
        if (credentials == null) {
            username = "匿名";
            return username;
        }
        if (credentials instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) credentials;
            username = userDetails.getUsername();
        } else {
            username = credentials.toString();
        }
        return username;
    }
}
